// 第三方库
import { useDispatch } from 'react-redux'
import { useHistory } from 'react-router'
// 组件库
import { Form, NavBar, Input, Button, Toast } from 'antd-mobile'
// action
import { login, getCode } from '@/store/actions/login'
// css
import styles from './Login.module.scss'
import { useRef, useEffect, useState } from 'react'
import { InputRef } from 'antd-mobile/es/components/input'
type LoginForm = {
  mobile: string
  code: string
}
export const Login = () => {
  // use 库
  const dispatch = useDispatch()
  const history = useHistory()
  // 数据状态
  const [form] = Form.useForm()
  const mobileRef = useRef<InputRef>(null)
  const [timeLeft, settimeLeft] = useState(0)
  // hooks 函数
  useEffect(() => {
    console.log('timeLeft 变化了')
    // 终止条件
    if (timeLeft === 0) {
      return
    }

    // 1、改变剩余倒计时，
    const timerId = setInterval(() => {
      settimeLeft(timeLeft - 1)
    }, 1000)

    // 2、清除timerId
    return () => {
      clearInterval(timerId)
    }
  }, [timeLeft])
  // 事件处理函数
  const onFinish = async (values: LoginForm) => {
    console.log('登录要提交的数据', values)
    await dispatch(login(values))
    Toast.show({
      content: '登录成功',
      duration: 500,
      afterClose: () => {
        // history.replace('/home')
        history.replace('/layout')
      }
    })
  }
  const handleGetCode = () => {
    // 手机号正确的情况下，发送验证码
    const mobile = form.getFieldValue('mobile') as string
    console.log(mobile)
    // 手机号不正确的情况下，设置光标到手机号输入框
    if (form.getFieldError('mobile').length > 0 || !mobile) {
      console.log('有问题，设置光标')
      return mobileRef.current?.focus()
    }

    console.log('发送验证码')
    dispatch(getCode(mobile))
    settimeLeft(5)
  }
  return (
    <div className={styles.root}>
      <NavBar></NavBar>

      <div className="login-form">
        <h2 className="title">账号登录</h2>

        <Form form={form} onFinish={onFinish}>
          <Form.Item
            className="login-item"
            name={'mobile'}
            validateTrigger={['onBlur', 'onChange']}
            rules={[
              { required: true, message: '请输入手机号' },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '手机号格式错误'
              }
            ]}
          >
            <Input ref={mobileRef} placeholder="请输入手机号" autoComplete="off" maxLength={11} />
          </Form.Item>

          <Form.Item
            className="login-item"
            name="code"
            rules={[
              { required: true, message: '请输入验证码' },
              { len: 6, message: '验证码需要6位' }
            ]}
            validateTrigger={['onBlur', 'onChange']}
            extra={
              <div className="code-extra" onClick={handleGetCode}>
                {timeLeft === 0 ? '发送验证码' : timeLeft}
              </div>
            }
          >
            <Input placeholder="请输入验证码" autoComplete="off" maxLength={6} />
          </Form.Item>

          {/* noStyle 表示不提供 Form.Item 自带的样式 */}
          <Form.Item noStyle shouldUpdate>
            {() => {
              // 获取到表单的状态值
              console.log('所有字段是否被操作过', form.isFieldsTouched(true))
              const isAllTouched = form.isFieldsTouched(true)
              console.log('操作过的结果', form.getFieldsError())
              // 判断错误数组的中每个字短的错误数组长度为0
              const noError = form.getFieldsError().every(item => item.errors.length === 0)
              return (
                <Button
                  disabled={!isAllTouched || !noError}
                  block
                  type="submit"
                  color="primary"
                  className="login-submit"
                >
                  登 录
                </Button>
              )
            }}
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
